﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DoubleH.Utility;
using System.Collections;
using System.Windows.Controls.DataVisualization.Charting;
using System.Reflection;
using Table=FCNS.Data.Table;

namespace ReportS.UC
{
    public struct CharProperty
    {
        public DataPointSeries Series { get; set; }
        public string ValueName { get; set; }//纵列绑定的数据库列明
        public string ValueTitle { get; set; }//标题
    }
    /// <summary>
    /// UCdataGrid.xaml 的交互逻辑
    /// </summary>
    public partial class UCdataGrid : UserControl
    {
        public UCdataGrid()
        {
            InitializeComponent();

            InitVar();
            InitEvent();
        }
        IEnumerable items = null;
        string chartKey = null;//datagridcolumn的排序列名，使用它来作为数据表要显示的数据
        CharProperty[] Series = null;
        double lastHeight = 0;

        DataTableText table = DataTableText.Null;
        public DataTableText TableText
        {
            set
            {
                table = value;
                dataGridExt1.InitColumns(table);
                dataGridExt1.CanUserAddRows = false;
            }
        }
        /// <summary>
        /// 设置明细的可见性
        /// </summary>
        public bool EnableDetail
        {
            set
            {
                checkBoxDetail.IsEnabled = value;
                if (!value)
                {
                    checkBoxDetail.IsChecked = false;
                    InitUI();
                }
            }
        }

        /// <summary>
        /// 设置图表的可见性
        /// </summary>
        public bool EnableChart
        {
            set
            {
                checkBoxChart.IsEnabled = value;
                if (!value)
                {
                    checkBoxChart.IsChecked = false;
                    InitUI();
                }
            }
        }


        private void InitVar()
        {
            //dataGridExt1.FormatLastRow = true;
        }

        private void InitEvent()
        {
            this.SizeChanged += (ss, ee) => lastHeight = row1.ActualHeight;
            gridSplitter.DragCompleted += (ss, ee) => lastHeight = row1.ActualHeight;
            buttonPrint.Click += (ss, ee) => PrintFunction.PrintList(dataGridExt1, table);
            checkBoxChart.Click += (ss, ee) => InitUI();
            checkBoxDetail.Click += (ss, ee) => InitUI();
            dataGridExt1.Sorting += (ss, ee) =>
            {
                string bind = ((Binding)((DataGridBoundColumn)ee.Column).Binding).Path.Path;
                if (string.IsNullOrEmpty(bind))
                    return;

                chartKey = bind;
                InitData();
            };
            //buttonDownlad.Click+=(ss,ee)=>
        }

        public void Init(IEnumerable ItemsSource, params CharProperty[] series)
        {
            items = ItemsSource;
            this.chartKey = ((Binding)((DataGridBoundColumn)dataGridExt1.Columns[0]).Binding).Path.Path;
            this.Series = series;
            InitUI();
            InitData();
            Sum();
        }

        private void InitUI()
        {
            if (checkBoxDetail.IsChecked.Value)
            {
                if (checkBoxChart.IsChecked.Value)
                    row1.Height = new GridLength(lastHeight);
                else
                    row1.Height = new GridLength(middleGrid.ActualHeight);
            }
            else
            {
                if (checkBoxChart.IsChecked.Value)
                    row1.Height = new GridLength(0);
                else
                    row1.Height = new GridLength(lastHeight);
            }
        }

        private void InitData()
        {
            if (checkBoxDetail.IsChecked.Value)
                dataGridExt1.ItemsSource = items;

            if (!checkBoxChart.IsChecked.Value)
                return;

            InitDataChart();
        }

        private void InitDataChart()
        {
            if (Series.Length == 0)
                return;

            chart1.Series.Clear();
            foreach (CharProperty cp in Series)
            {
                List<KeyValuePair<string, double>> valueList = new List<KeyValuePair<string, double>>();
                Type type = items.AsQueryable().ElementType;
                PropertyInfo pKey = type.GetProperty(chartKey);
                //MessageBox.Show(cp.IndependentValuePath);
                PropertyInfo pValue = type.GetProperty(cp.ValueName);
                if (pKey == null || pValue == null)
                    continue;

                foreach (var item in items)
                {
                    object kyObj = pKey.GetValue(item, null);
                    if (kyObj == null)
                        continue;

                    string ky = chartKey.Contains("DateTime") ? ((DateTime)kyObj).ToString("yyyy-MM-dd") : kyObj.ToString();
                    object obj = pValue.GetValue(item, null);
                    double kv = obj == null ? 0 : (double)obj;
                    KeyValuePair<string, double>? kvp = valueList.Find(f => f.Key == ky);
                    if (kvp == null)
                        valueList.Add(new KeyValuePair<string, double>(ky, kv));
                    else
                    {
                        kv = kv + kvp.Value.Value;
                        valueList.Remove(kvp.Value);
                        valueList.Add(new KeyValuePair<string, double>(ky, kv));
                    }
                }

                cp.Series.DependentValuePath = "Value";
                cp.Series.IndependentValuePath = "Key";
                cp.Series.Title = cp.ValueTitle;
                cp.Series.ItemsSource = valueList;
                chart1.Series.Add(cp.Series);
            }
        }
        /// <summary>
        /// 在标题显示统计数
        /// </summary>
        private void Sum()
        {
            if (!dataGridExt1.HasItems)
                return;

            PropertyInfo[] pi = dataGridExt1.Items[0].GetType().GetProperties();
            foreach (PropertyInfo info in pi)
            {
                if (!info.CanRead)
                    continue;
                string name = info.PropertyType.Name;
                if (name != "Int64" && name != "Int32" && name != "Double" && !name.Contains("Nullable"))
                    continue;

                foreach (DataGridTextColumn column in dataGridExt1.Columns)
                {
                    if (((Binding)column.Binding).Path.Path == info.Name)
                    {
                        string header = column.Header.ToString();
                        if (header.Contains("："))
                            header = header.Split('：')[0].Trim();
                        double dou = 0;

                        foreach (object obj in items)
                        {
                            object ob = info.GetValue(obj, null);
                            if (ob != null)
                                dou += Convert.ToDouble(ob);
                        }

                        column.Header = header + "\r\n：" + Math.Round(dou, Table.SysConfig.SysConfigParams.DecimalPlaces) + "";
                        break;
                    }
                }
            }
        }
    }
}